let parentCategoryJson
let childCategoryJson

$(document).ready(function () {
    //获取父菜单列表
    getParentItemList();
    getCategoryInfo();


});parentCategory
//数据表格
layui.use(['table','upload','form','laydate'], function() {
    let table = layui.table
        , form = layui.form
        , upload = layui.upload
        , laydate = layui.laydate;
    form.render();

    function getDate(){
        let date = new Date().Format("yyyy-MM-dd HH:mm:ss");
        return date;
    }

    laydate.render({
        elem: '#chooseDate'
        , type: 'datetime'
        , position: "fixed"
        , format: 'yyyy-MM-dd HH:mm:ss'
        , min: getDate()
        ,trigger:'click'
    });

    //表格渲染
    table.render({
        elem: '#itemList'
        , method: "post"
        , url: '/getSecKillItemList'
        , toolbar: '#topTools' //开启头部工具栏，并为其绑定左侧模板
        , title: '商品列表'
        , totalRow: true
        , request: {
            pageName: 'curPage',
            limitName: 'pageSize'
        }, parseData: function (res) {
            return {
                "code": res.code == 200 ? 0 : -1,
                "msg": "",
                "count": res.data.count,
                "data": res.data.data
            }
        }
        , cols: [
            [
                {field: 'id', title: 'ID', width: 60, fixed: 'left', unresize: true, sort: true}
                , {field: 'itemName', title: '商品名', width: 100}
                , {field: 'catId', title: '分类', width: 100}
                , {
                field: 'onOffStatus',
                title: '状态',
                width: 100,
                templet: "<div>{{(d.onOffStatus == 1)?'上架':'下架'}}</div>"
            }
                , {
                field: 'createTime',
                title: '创建日期',
                width: 170,
                templet: "<div>{{layui.util.toDateString(d.createdTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"
            }, {
                field: 'expiredTime',
                title: '截止日期',
                width: 170,
                templet: "<div>{{layui.util.toDateString(d.expiredTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"
            }
                , {field: 'stock', title: '库存', width: 100}
                , {field: 'price', title: '秒杀价', width: 100,templet:function (data) {
                    let price = parseFloat(data.price).toFixed(2);
                    return price;}}
                , {field: 'content', title: '商品内容', width: 100}
                , {fixed: 'right', title: '操作', toolbar: '#itemOperator', width: 200}
            ]]
        , page: true
        , done: function (res, curr, count) {

            $("[data-field='rootCatId']").children().each(function () {
                let rootCatId = $(this).text();
                $(this).text(parentCategoryJson[rootCatId])

            })
            $("[data-field='catId']").children().each(function () {
                let catId = $(this).text();
                $(this).text(childCategoryJson[catId])

            })
            getParentCategoryList();
        }
    });

    function selectItem() {
        let key = $("#searchItemName").val();
        let catId = $("#childCategorySelect").val();
        let rootCatId = $("#parentCategorySelect").val();
        table.reload('itemList', {
            method: 'post'
            , where: {
                'itemName': key,
                'catId': catId,
            }
            , page: {
                curr: 1
            }
            , done: function () {
                $("[data-field='rootCatId']").children().each(function () {
                    let rootCatId = $(this).text();
                    $(this).text(parentCategoryJson[rootCatId]);
                })
                $("[data-field='catId']").children().each(function () {
                    let catId = $(this).text();
                    $(this).text(childCategoryJson[catId])
                })
                getParentCategoryListSelect(rootCatId);
                getChildCategoryList(rootCatId);
                form.render('select')
                if (rootCatId != '' || rootCatId != undefined || rootCatId != null) {
                    $("#selectChildCategory").removeClass("layui-hide");
                }

                $("#selectChildCategory option").each(function () {
                    if ($(this).attr("value") == catId) {
                        $(this).prop("selected", 'selected');
                    }
                });
                form.val("itemSearchForm", {
                    "searchItemName": key,
                });

                form.render('select');
                $("#searchItemName").val(key);
            }

        });
    }
    function reloadTable() {
        let key = $("#searchItemName").val();
        let catId = $("#childCategorySelect").val();
        let rootCatId = $("#parentCategorySelect").val();
        let currentPage=$(".layui-laypage-em").next().html();
        table.reload('itemList',{
            method: 'post'
            ,where:{
                'itemName':key,
                'catId':catId,
                'rootCatId':rootCatId
            }
            ,page: {
                curr:currentPage
            }
            ,done:function () {
                $("[data-field='rootCatId']").children().each(function () {
                    let rootCatId = $(this).text();
                    $(this).text(parentCategoryJson[rootCatId]);
                })
                $("[data-field='catId']").children().each(function () {
                    let catId = $(this).text();
                    $(this).text(childCategoryJson[catId])
                });
                selectTargetKeep(rootCatId,catId);
                form.val("itemSearchForm",{
                    "searchItemName":key,
                });

                form.render();
                $("#searchItemName").val(key);
            }

        });
    }
    //监听头部工具事件
    table.on('toolbar(itemList)', function (obj) {
        switch (obj.event) {
            case 'addItem' :
                createItemModel();
                break;
            case 'searchItem':
                selectItem();
                form.render('select');
                break;
            case 'reloadTable':
                reloadTable();
                break;
        }


    });


    //监听行工具事件
    table.on('tool(itemList)', function (obj) {
        let data = obj.data;

        if (obj.event == "edit") {
            editItemModel(data);
        } else if (obj.event == "enable") {
            $.ajax({
                url: "/changeOnOffStatus",
                method: "post",
                charset: "UTF-8",
                dataType: "json",
                contentType: "application/json;charset=utf-8;",
                data: JSON.stringify(data),
                success: function (data) {
                    if (data == "1") {
                        alert("上架成功");
                        reloadTable();
                        layer.close(layer.index);
                    } else {
                        alert("上架失败");
                        layer.close(layer.index);
                    }
                }
            });
        } else if (obj.event === "disable") {
            $.ajax({
                url: "/changeOnOffStatus",
                method: "post",
                charset: "UTF-8",
                dataType: "json",
                contentType: "application/json;charset=utf-8;",
                data: JSON.stringify(data),
                success: function (data) {
                    if (data == "1") {
                        alert("下架成功");
                        reloadTable();
                        layer.close(layer.index);
                    } else {
                        alert("下架失败");
                        layer.close(layer.index);
                    }
                }
            });
        }
    });

    form.on('select(parentItem)', function (data) {
        let parentId = data.value;
        getChildItemList(parentId,form);
        form.render();
    });

    form.on('select(parentCategory)', function (data) {
        let parentId = data.value;
        getChildCategoryList(parentId);
        if (parentId != "") {
            $("#selectChildCategory").removeClass("layui-hide");
        } else {
            $("#selectChildCategory").addClass("layui-hide");
        }

        form.render();
    });
    //图片上传
    upload.render({
        elem: '#secKillItemIcon'
        ,url:'/uploadMainItemImage'
        ,size:10485760 //10M
        ,accept:'images'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            $("#demo1").empty();
            obj.preview(function(index, file, result){
                $('#demo1').append('<img width="60" height="60" src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img"><a>&nbsp;&nbsp;&nbsp;</a>')
            });
        }
        ,done:function (res) {
            let data = res.data;
            let iconImage = $("#iconImage");
            if (iconImage.val() == ""){
                iconImage.val(data)
            }

        }
    });
    function getParentCategoryList() {
        $.ajax({
            url: "/getParentCategory",
            method: "post",
            charset: "UTF-8",
            async: true,
            success: function (res) {
                let parentCategorySelect = $("#parentCategorySelect");
                parentCategorySelect.empty();
                parentCategorySelect.append("<option value=" + "" + ">" + "请选择分类" + "</option>");
                let parentCategoryList = res.data;
                $.each(parentCategoryList, function (index, value) {
                    parentCategorySelect.append("<option value='" + value.id + "'" + ">" + value.name + "</option>");
                });
                form.render('select');
                // getChildCategoryList($("#parentCategorySelect").val());
            }

        })
    }

    function getParentCategoryListSelect(rootCatId) {
        $.ajax({
            url: "/getParentCategory",
            method: "post",
            charset: "UTF-8",
            async: true,
            success: function (res) {
                let parentCategorySelect = $("#parentCategorySelect");
                parentCategorySelect.empty();
                parentCategorySelect.append("<option name='parentCategory' value=" + "" + ">" + "请选择分类" + "</option>");
                let parentCategoryList = res.data;
                $.each(parentCategoryList, function (index, value) {
                    parentCategorySelect.append("<option name='parentCategory' value='" + value.id + "'" + ">" + value.name + "</option>");
                });
                $("#selectParentCategory option").each(function () {
                    if ($(this).attr("value") == rootCatId) {
                        $(this).prop("selected", 'selected');
                    }
                });
                form.render('select');
            }

        });
    }

    function getChildCategoryList(parentId) {
        $.ajax({
            url: "/getChildCategory",
            method: "post",
            charset: "UTF-8",
            data: "parentId=" + parentId,
            async: false,
            success: function (res) {
                let childCategorySelect = $("#childCategorySelect");
                childCategorySelect.empty();
                let chileCategoryList = res.data;
                childCategorySelect.append("<option value=''" + "'" + ">" + "请选择分类" + "</option>");
                if (parentId != "") {
                    $.each(chileCategoryList, function (index, value) {
                        childCategorySelect.append("<option value='" + value.id + "'" + ">" + value.name + "</option>");
                    });
                }
                form.render('select');
            }

        })

    };

    function cleanerItemText() {
        $("#itemId").val("");
        $("input[name='itemName']").val("");
        $("input[name='stock']").val("");
        $("input[name='secKillPrice']").val("");
        $("input[name='content']").val("");
        $("#chooseDate").val("");


    }

    //创建商品
    function createItem() {
        //商品基本属性
        let itemName = $("input[name='itemName']").val();
        let stock = $("input[name='stock']").val();
        let childId = $("select[name='childItemSelect']").val();
        let price = $("input[name='secKillPrice']").val();
        let content = $("input[name='content']").val();
        let expiredTime = $("#chooseDate").val();
        if (expiredTime == '' || expiredTime == null){
            alert("尚未选择截止日期！");
            return;
        }
        let icon = JSON.parse($("#iconImage").val())['url'];
        let itemJson = {
            "itemName": itemName,
            "catId": childId,
            "stock": stock,
            "price": price,
            "content": content,
            "onOffStatus": 1,
            "icon":icon,
            "expiredTime":expiredTime
        };


        // let itemInfo = {"aItemSecKill": itemJson};

        $.ajax({
            url: "/addSecKillItem",
            method: "post",
            charset: "UTF-8",
            dataType: "json",
            cache: false,
            contentType: "application/json;charset=utf-8;",
            data:JSON.stringify(itemJson),
            success: function (data) {
                if (data != "0") {
                    alert("新增商品成功");
                    cleanerItemText();
                    location.reload();
                    // layer.close(layer.index);
                } else {
                    alert("新增商品失败");
                    cleanerItemText();
                    // layer.close(layer.index);
                }
            }
        });


    }

    function editItemModel(data) {
        $("#itemId").val(data.id);
        $("div[name='secKillItemName'] ").addClass("layui-hide");
        $("div[name='secKillItemName']").addClass("layui-hide");
        $("div[name='itemParentCat']").addClass("layui-hide");
        $("div[name='itemChildCat']").addClass("layui-hide");
        $("div[name='itemStock']").addClass("layui-hide");
        $("div[name='secKillPrice']").addClass("layui-hide");
        $("div[name='secKillItemContent']").addClass("layui-hide");
        $("div[name='secKillIcon']").addClass("layui-hide");
        $("#chooseDate").val(data.expiredTime);

        layui.use(['layer'], function () {
            let layer = layui.layer, $ = layui.$;
            layer.open({
                type: 1,
                anim: 4,
                area: ['100%', '100%'],
                title: '修改商品',
                shadeClose: false,
                content: $('#createItem')
            });
        });
        $("#btn_yes").on('click', function () {
            editItem();
        })
    }


    //修改商品
    function editItem() {
        //商品基本属性
        let itemId = $("#itemId").val();
        let expiredTime = $("#chooseDate").val();
        let itemJson = {
            "id": itemId,
            "expiredTime": expiredTime
        };

        // let itemInfo = {itemJson};
        $.ajax({
            url: "/changeExpiredTime",
            method: "post",
            charset: "UTF-8",
            dataType: "json",
            cache: false,
            contentType: "application/json;charset=utf-8;",
            data: JSON.stringify(itemJson),
            success: function (data) {
                if (data != "0") {
                    alert("修改商品成功");
                    cleanerItemText();
                    location.reload();
                    // layer.close(layer.index);
                } else {
                    alert("修改商品失败");
                    cleanerItemText();
                    // layer.close(layer.index);
                }
            }
        });

    }


    function createItemModel() {
        $("div[name='secKillItemName']").removeClass("layui-hide");
        $("div[name='itemParentCat']").removeClass("layui-hide");
        $("div[name='itemChildCat']").removeClass("layui-hide");
        $("div[name='itemStock']").removeClass("layui-hide");
        $("div[name='secKillPrice']").removeClass("layui-hide");
        $("div[name='secKillItemContent']").removeClass("layui-hide");
        $("div[name='secKillIcon']").removeClass("layui-hide");
        cleanerItemText();
        layui.use(['layer'], function () {
            let layer = layui.layer, $ = layui.$;
            layer.open({
                type: 1,
                anim: 4,
                area: ['100%', '100%'],
                title: '新增商品',
                shadeClose: false,
                content: $('#createItem')
            });
        });
        $("#btn_yes").on('click', function () {
            createItem();
        })
    }





});
function getParentItemList() {
    $.ajax({
        url: "/getParentCategory",
        method: "post",
        charset: "UTF-8",
        async: false,
        success: function (res) {
            let parentItemSelect = $("#parentItemSelect");
            parentItemSelect.empty();
            let parentItemList = res.data;
            $.each(parentItemList, function (index, value) {
                parentItemSelect.append("<option value='" + value.id + "'" + ">" + value.name + "</option>");
            });
            getChildItemList($("#parentItemSelect").val());
        }

    })
}


function getChildItemList(parentId,form) {
    $.ajax({
        url: "/getChildCategory",
        method: "post",
        charset: "UTF-8",
        data: "parentId=" + parentId,
        async: true,
        success: function (res) {
            let childItemSelect = $("#childItemSelect");
            childItemSelect.empty();
            let childItemList = res.data;
            $.each(childItemList, function (index, value) {
                childItemSelect.append("<option value='" + value.id + "'" + ">" + value.name + "</option>");
            });
            if (form != undefined){
                form.render('select');
            }
        }

    });
}

function getCategoryInfo() {
    let parentCategory;
    let childCategory;
    let p = $("#parentCategoryList");
    let c = $("#childCategoryList");
    $.ajax({
        url: "getItemCategory"
        , method: "post"
        , success: function (data) {
            parentCategory = "{";
            childCategory = "{";
            $.each(data.parentCategory, function (index, item) {
                parentCategory = parentCategory + '"' + item.id + '"' + ':"' + item.name + '",'

            });
            parentCategory = parentCategory.replace(/(,$)/g, '') + "}"
            $.each(data.childCategory, function (index, item) {
                childCategory = childCategory + '"' + item.id + '"' + ':"' + item.name + '",'
            });
            childCategory = childCategory.replace(/(,$)/g, '') + "}"

            parentCategoryJson = JSON.parse(parentCategory)
            childCategoryJson = JSON.parse(childCategory)

        }
    });
}

Date.prototype.Format = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}